package controllers

import dao._
import org.joda.time.DateTime
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.Utils

import java.io.File
import javax.inject.Inject
import implicits.Implicits._
import models.Tables._
import play.api.libs.json.Json
import tool.Tool

import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 10/12/2021
 */
class DataInsertController @Inject()(cc: ControllerComponents)(
  implicit val dataDao: DataDao,
  implicit val annoDao: AnnoDao,
  implicit val geneDao: GeneDao,
) extends AbstractController(cc) {

  val parentDir = new File("E:\\snp_database\\test")

  def insertData = Action.async {
    val startTime = System.currentTimeMillis()
    val file = new File(parentDir, "SNP条目汇总-第二次补充.xlsx")
    val maps = file.xlsxLines().lineSeqMap
    val rows = maps.map { map =>
      DataRow(
        snpNumber = map("SNP位点（rs号）（必填）"),
        gene = map("基因（可选）"),
        nutrient = map("相关营养素（必填）"),
        or = map("OR（可选）"),
        p = map("P值（可选）"),
        articleTitle = map("文章名称（必填）"),
        articleDoi = map("文章DOI号（必填）"),
        id = map("序号")
      )
    }.distinctBy(_.id)
    dataDao.deleteAll.flatMap(_ => dataDao.insertAll(rows)).map { _ =>
      Ok("success!" + "\t" + rows.size + "\t" + Utils.getTime(startTime))
    }
  }

  def insertAnno = Action.async {
    val startTime = System.currentTimeMillis()
    val rows = Tool.rsDir.myListFiles.filter { dir =>
      dir.getName.startsWith("rs") && dir.getName != "rs20607903"
    }.map { dir =>
      val jsonFile = new File(dir, s"${dir.getName}.json")
      val json = Json.parse(jsonFile.str)
      val summaryJson = (json \ "summary")
      AnnoRow(
        rsNumber = dir.getName,
        organism = (summaryJson \ "Organism").as[String],
        position = (summaryJson \ "Position").as[String],
        alleles = (summaryJson \ "Alleles").as[String],
        variationType = (summaryJson \ "Variation Type").as[String].mySplit("\\s+").head,
        frequency = (summaryJson \ "Frequency").as[List[String]],
        clinicalSignificance = (summaryJson \ "Clinical Significance").as[String],
        geneConsequence = (summaryJson \ "Gene : Consequence").as[String],
        publications = (summaryJson \ "Publications").as[String]
      )
    }
    annoDao.deleteAll.flatMap(_ => annoDao.insertAll(rows)).map { _ =>
      Ok("success!" + "\t" + rows.size + "\t" + Utils.getTime(startTime))
    }
  }

  def insertGene = Action.async {
    val startTime = System.currentTimeMillis()
    val parentDir = new File("E:\\snp_database\\test")
    val annoDir = new File(parentDir, "anno")
    val rows = annoDir.myListFiles.filter { dir =>
      val file = new File(dir, s"or.txt")
      file.exists()
    }.flatMap { dir =>
      dir.myListFiles.filter { file =>
        file.getName.matches("^K\\d+\\.txt$")
      }.map { file =>
        val koMap = Tool.getKoMap(file)
        GeneRow(
          entry = koMap("ENTRY").head.mySplit("\\s+").head,
          symbol = koMap("SYMBOL").head,
          name = koMap("NAME").head,
          pathway = koMap.getOrElse("PATHWAY", List.empty),
        )
      }

    }
    geneDao.deleteAll.flatMap(_ => geneDao.insertAll(rows)).map { _ =>
      Ok("success!" + "\t" + rows.size + "\t" + Utils.getTime(startTime))
    }
  }


}
